﻿using Xejen.Communication.Configuration;
using Xejen.Communication.Demos.Common;
using Xejen.Communication.Endpoints;
using Xejen.Communication.Soap;
using Xejen.Communication.Soap.Abstract;
using Xejen.Communication.Soap.Communicator;
using Xejen.Communication.Soap.Configuration;
using Xejen.Communication.Soap.Endpoints;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Xejen.Communication.Wcf.Demos
{
    public partial class MainForm : Form
    {
        private ISoapCommunicator _communicator;
        public MainForm(ISoapCommunicator communicator)
        {
            //以下3种方式均可以注册心跳检测逻辑
            //第1种：
            //communicator.Heartbeat.LocalHeartbeatCheck = () =>
            //{
            //    Debug.WriteLine($"本地心跳检测时间：{DateTime.Now.ToString()}");
            //    byte[] buffer = Guid.NewGuid().ToByteArray();
            //    var value = BitConverter.ToInt64(buffer, 0);

            //    return value % 2 == 1;
            //};
            //communicator.Heartbeat.RemoteHeartbeatCheck = () =>
            //{
            //    Debug.WriteLine($"远端心跳检测时间：{DateTime.Now.ToString()}");
            //    byte[] buffer = Guid.NewGuid().ToByteArray();
            //    var value = BitConverter.ToInt64(buffer, 0);

            //    return value % 2 == 0;
            //};
            //第2种
            //communicator.Heartbeat.RegisterHeartbeatChecker(new HeartbeatChecker());
            //第3种
            communicator.Heartbeat.RegisterHeartbeatChecker<HeartbeatConfig, HeartbeatChecker>();

            _communicator = communicator;

            InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            _communicator.Heartbeat.LocalAliveChanged += (object sender, AliveStatusEventArgs args) =>
            {
                Debug.WriteLine($"设备是否在线：{args.CurrentStatus}");

                Invoke((MethodInvoker)(() =>
                {
                    LocalAliveLabel.Text = args.CurrentStatus.ToString();
                }));
            };
            _communicator.Heartbeat.RemoteAliveChanged += (object sender, AliveStatusEventArgs args) =>
            {
                Debug.WriteLine($"远端是否在线：{args.CurrentStatus}");

                Invoke((MethodInvoker)(() =>
                {
                    RemoteAliveLabel.Text = args.CurrentStatus.ToString();
                }));
            };
        }

        /// <summary>
        /// 可以正常使用
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            //#region 原始的请求方式，全部api自己构建
            //SoapConfig config = new SoapConfig() { };
            //SoapRequestHandler<WcfInvoker, SoapConfig,WcfAddress> handle = new SoapRequestHandler<WcfInvoker, SoapConfig,WcfAddress>();

            //SoapCommunicator<WcfInvoker, WcfAddress> communicator = new SoapCommunicator<WcfInvoker, WcfAddress>(config, new WcfInvokerCreator(), handle);
            //var result1 = await communicator.RequestAsync(new SoapCommunicationAddress<WcfAddress>
            //{
            //    RequestAddress = new Address<WcfAddress>
            //    {
            //        Value = new WcfAddress
            //        {
            //            RequestUri = "http://192.168.3.164:85/Service1.svc",
            //            MethodName = "GetData",
            //            ServiceType = typeof(IService1)
            //        }
            //    }
            //}, new List<object> { 34 }, 3000, default);

            //var result2 = await communicator.RequestAsync<List<object>>(new SoapCommunicationAddress<WcfAddress>
            //{
            //    RequestAddress = new Address<WcfAddress>
            //    {
            //        Value = new WcfAddress
            //        {
            //            RequestUri = "http://192.168.3.164:85/Service1.svc",
            //            MethodName = "GetDataUsingDataContract",
            //            ServiceType = typeof(IService1)
            //        }
            //    }
            //}, new List<object> { new CompositeType { BoolValue = false, StringValue = "fdsasa11" } });

            //var returnData = result2.ReturnData;
            //#endregion
        }

        /// <summary>
        /// 可以正常使用
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button2_Click(object sender, EventArgs e)
        {
            #region 使用依赖注入的方式构建请求
            var result1 = await _communicator.InvokeServiceAsync(new WcfAddressWrapper
            {
                RequestAddress = new Address<WcfAddress>
                {
                    Value = new WcfAddress
                    {
                        RequestUri = "http://192.168.3.164:85/Service1.svc",
                        MethodName = "GetData",
                        ServiceType = typeof(IService1)
                    }
                }
            }, new List<object> { 34 }, 3000, default);

            var result2 = await _communicator.InvokeServiceAsync(new WcfAddressWrapper
            {
                RequestAddress = new Address<WcfAddress>
                {
                    Value = new WcfAddress
                    {
                        RequestUri = "http://192.168.3.164:85/Service1.svc",
                        MethodName = "GetDataUsingDataContract",
                        ServiceType = typeof(IService1)
                    }
                }
            }, new List<object> { new CompositeType { BoolValue = false, StringValue = "fdsasa11" } });

            var returnData = result2.ReturnData;
            #endregion
        }

        /// <summary>
        /// 
        /// </summary>
        [ServiceContract]
        public interface IService1
        {
            /// <summary>
            /// 
            /// </summary>
            /// <param name="value"></param>
            /// <returns></returns>
            [OperationContract]
            string GetData(int value);
            /// <summary>
            /// 
            /// </summary>
            /// <param name="composite"></param>
            /// <returns></returns>
            [OperationContract]
            CompositeType GetDataUsingDataContract(CompositeType composite);

            /// <summary>
            /// /
            /// </summary>
            /// <param name="x"></param>
            /// <param name="y"></param>
            /// <returns></returns>
            [OperationContract]
            double Add(double x, double y);
            /// <summary>
            /// 
            /// </summary>
            /// <param name="first"></param>
            /// <param name="last"></param>
            /// <returns></returns>
            [OperationContract]
            string GetUserName(string first, string last);
        }

        /// <summary>
        /// 
        /// </summary>
        [DataContract]
        public class CompositeType
        {
            bool boolValue = true;
            string stringValue = "Hello ";
            /// <summary>
            /// 
            /// </summary>
            [DataMember]
            public bool BoolValue
            {
                get { return boolValue; }
                set { boolValue = value; }
            }
            /// <summary>
            /// 
            /// </summary>
            [DataMember]
            public string StringValue
            {
                get { return stringValue; }
                set { stringValue = value; }
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            //MiBatchCompleteSfcAndAdujustQtyServiceClient client = new MiBatchCompleteSfcAndAdujustQtyServiceClient();
            //var response = await client.MiBatchCompleteSfcAndAdujustQtyAsync(new MiBatchCompleteSfcAndAdujustQtyRequest1());

            //var msg = response.MiBatchCompleteSfcAndAdujustQtyResponse.returnField.messageField;

            //#region 原始的请求方式，全部api自己构建
            //SoapConfig config = new SoapConfig() { };
            //SoapRequestHandler<WcfInvoker, SoapConfig, WcfAddress> handle = new SoapRequestHandler<WcfInvoker, SoapConfig, WcfAddress>();

            //var model = new MiBatchCompleteSfcAndAdujustQtyRequest1 { };
            //SoapCommunicator<WcfInvoker, WcfAddress> communicator = new SoapCommunicator<WcfInvoker, WcfAddress>(config, new WcfInvokerCreator(), handle);
            //var result1 = await communicator.RequestAsync(new SoapCommunicationAddress<WcfAddress>
            //{
            //    RequestAddress = new Address<WcfAddress>
            //    {
            //        Value = new WcfAddress
            //        {
            //            RequestUri = "http://192.168.3.164:85/Mes/WebServices/CATL/MiBatchCompleteSfcAndAdujustQtyService.svc",
            //            MethodName = "MiBatchCompleteSfcAndAdujustQty",
            //            ServiceType = typeof(IMiBatchCompleteSfcAndAdujustQtyService)
            //        }
            //    }
            //}, new List<object> { model }, 3000, default);

            //var returnData = result1.ReturnData as ServiceReference1.MiBatchCompleteSfcAndAdujustQtyResponse11;
            //#endregion
        }
    }
}
